const { Sequelize } = require('sequelize');
require('dotenv').config();

// 检查必要的环境变量
const requiredEnvVars = ['MYSQL_HOST', 'MYSQL_USER', 'MYSQL_PASSWORD', 'MYSQL_DATABASE'];
const missingEnvVars = requiredEnvVars.filter(envVar => !process.env[envVar]);

if (missingEnvVars.length > 0) {
  console.error('缺少必要的环境变量:', missingEnvVars.join(', '));
  process.exit(1);
}

const sequelize = new Sequelize(
  process.env.MYSQL_DATABASE,
  process.env.MYSQL_USER,
  process.env.MYSQL_PASSWORD,
  {
    host: process.env.MYSQL_HOST,
    dialect: 'mysql',
    logging: console.log, // 启用 SQL 查询日志
    pool: {
      max: 5,
      min: 0,
      acquire: 30000,
      idle: 10000
    },
    define: {
      timestamps: false, // 禁用默认的时间戳字段
      underscored: true, // 使用下划线命名
      freezeTableName: true // 表名不自动复数化
    }
  }
);

// 测试数据库连接
const testConnection = async () => {
  try {
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 测试数据库权限
    await sequelize.query('SELECT 1+1 AS result');
    console.log('数据库权限检查通过');
    
    return true;
  } catch (error) {
    console.error('数据库连接失败:', error.message);
    if (error.original) {
      console.error('原始错误:', error.original.message);
    }
    throw error; // 重新抛出错误以便上层处理
  }
};

module.exports = {
  sequelize,
  testConnection
};